package com.juzishuke.margin.framework.web.feign;

import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.google.common.base.Optional;
import com.juzishuke.margin.framework.AppContext;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

import static com.juzishuke.margin.framework.web.WebConstants.DISCOVERY_KEY_VERSION;
import static com.juzishuke.margin.framework.web.WebConstants.WEB_ROUTE_KEY_VERSION;

/**
 * @author : libo@juzishuke.com
 * @Title :
 * @Description :
 * @date : 2024/4/8 19:32
 * @since :1.0
 */
@Slf4j
public class MetaVersionIRule extends ZoneAvoidanceRule implements IRule {
    
    
    @Override
    public Server choose(final Object key) {
        String metadataVersion = AppContext.getThreadLocal(DISCOVERY_KEY_VERSION);
        ILoadBalancer lb = getLoadBalancer();
        List<Server> servers = lb.getAllServers();
        servers = servers.stream().filter(e -> {
            NacosServer nacosServer = (NacosServer) e;
            return StringUtils.equalsAnyIgnoreCase(metadataVersion, nacosServer.getMetadata().get(
                    DISCOVERY_KEY_VERSION));
        }).collect(Collectors.toList());
        log.info("MetaVersionIRule 根据version ={} , 待选实例: {} ", metadataVersion, servers.size());
        Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(servers, key);
        if (server.isPresent()) {
            Server s1 = server.get();
            log.info("MetaVersionIRule 根据version ={} , 对应的实例: {} ", metadataVersion, s1);
            return s1;
        } else {
            log.info("MetaVersionIRule 根据version ={} , 对应的实例: {} ", metadataVersion, null);
            return null;
        }
    }
}
